<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/24
 * Time: 17:14
 */

namespace AdminsBundle\Helper;

use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use AdminsBundle\Helper\Pagination;

class MyController extends Controller {
    public function chkLogin()
    {
        $session = new Session();
        if ($session->has('adminId')) {
            return  $session->get('adminId');
        } else {
            header("location:".$this->generateUrl("adminLoginPage"));exit;
        }
    }

    /**
     * json 格式输出结果
     * @param $status
     * @param $info
     * @param array $data
     * @return Response
     */
    public function json_out ($status,$info,$data = array())
    {
        if (!is_array($data)) {
            $data = (array)$data;
        }
        $data = array(
            "s"=> $status?$status:0,
            "i"  => $info?$info:"",
            "d"  => !empty($data)?$data:"",
        );
        return new Response(json_encode($data),200,array("content-type"=>"application/json"));
    }

    /**
     * js弹窗提示结果后跳转
     * @param $path
     * @param $msg
     * @return Response
     */
    public function js_out($path,$msg)
    {
        $data = array(
            "url"   => $path,
            "msg"   => $msg,
        );
        return $this->render("AdminsBundle::message.html.twig",$data);
    }

    /**
     * 获取必填参数
     * @param $paramName
     * @return bool|mixed
     */
    public function getParamRequired($paramName)
    {
        $request = Request::createFromGlobals();
        if ($request->request->has("$paramName")) {
            return $request->get("$paramName");
        }
        if ($request->query->has("$paramName")) {
            return $request->get("$paramName");
        }
        return false;
    }

    /**
     * @param $base_url
     * @param $total_rows
     * @param int $per_page
     * @return array
     */
    public function creatPage($base_url,$total_rows,$per_page = 10)
    {
        $config['first_url'] = $base_url;
        $config['base_url'] = $base_url;
        $config['total_rows'] = $total_rows;
        $config['per_page'] = $per_page;
        $config['reuse_query_string'] = TRUE;

        //分页基础配置
        $config['num_links'] = 3;
        $config['first_link'] = '首页';
        $config['prev_link'] = '«上一页';
        $config['cur_tag_open'] = '<span class="current">';
        $config['cur_tag_close'] = '</span>';
        $config['next_link'] = '下一页»';
        $config['last_link'] = '末页';

        $pageBuilder = new Pagination($config);
        $page =  $pageBuilder->create_links();
        return array(
            "total"     => $total_rows,
            "perPage"   => $per_page,
            "page"      => $page
        );
    }


    public function createMyForm($entityName , $entity , $actionUrl = "" , $method = "POST")
    {
        $config = array(
            "entity"   => $entity,
            "actionUrl"   => $actionUrl,

        );
        $options = array(
            "attr"  => array(
                "action" => $actionUrl,
                "method" => $method,
            ),
        );

        $form = $this->createFormBuilder($config["entity"],$options)->getForm();
        $m = $this->getDoctrine()->getManager();
        $formRows = new MyForms($m);
        foreach ($formRows->$entityName() as $key => $param) {
            $form->add($key,$this->type2RealType($param["showType"]),$this->basicParam($param["showType"],$param["label"],$param["dataType"],$param["option"]));
        }
        return $form;
    }

    private function type2RealType($type)
    {
        switch ($type) {
            case "article":
                $realType = "textarea";
                break;
            case "select":
                $realType = "choice";
                break;
            case "radio":
                $realType = "choice";
                break;
            case "checkbox":
                $realType = "choice";
                break;
            case "pic":
                $realType = "search";
                break;
            case "pics":
                $realType = "search";
                break;
            case "datetime":
            case "time":
            case "date":
                $realType = "text";
                break;
            default:
                $realType = $type;

        }
        return $realType;
    }

    public function basicParam($type,$name,$dataType,$option)
    {
        $attr = isset($option["attr"])?$option["attr"]:array();
        $attr = array_merge($attr,array("datatype"=>$dataType));
        $otherParam = isset($option["other"])?array_merge(array("label"=>$name),$option["other"]):array("label"=>$name);
        switch ($type) {
            case "select"://选择
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-single-select",
                    ),$attr),
                    "expanded"=>"0",
                    "multiple"=>"0",
                ),$otherParam);
                return $basic;
                break;
            case "radio"://单选
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-multi-radio",
                    ),$attr),
                    "expanded"=>"1",
                    "multiple"=>"0",
                ),$otherParam);
                return $basic;
                break;
            case "checkbox"://多选
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-multi-checkbox",
                    ),$attr),
                    "expanded"=>"1",
                    "multiple"=>"1",
                ),$otherParam);
                return $basic;
                break;
            case "article"://富文本
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "editor",
                    ),$attr),
                    "required"  => False
                ),$otherParam);
                return $basic;
                break;
            case "date"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"input rule-date-input" ,
                        'onfocus'=>"WdatePicker({dateFmt:'yyyy-MM-dd'})" ,
                        'datatype'=>"/^\s*$|^\d{4}\-\d{1,2}\-\d{1,2}$/" ,
                        'errormsg'=>"请选择正确的日期",
                    ),$attr)
                ),$otherParam);
                return $basic;
                break;
            case "time"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"input rule-date-input" ,
                        'onfocus'=>"WdatePicker({dateFmt:'HH:mm:ss'})" ,
                        'datatype'=>"/^(\d{1,2}:){2}\d{1,2}$/" ,
                        'errormsg'=>"请选择正确的日期",
                    ),$attr)
                ),$otherParam);
                return $basic;
                break;
            case "datetime"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"input rule-date-input" ,
                        'onfocus'=>"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" ,
                        'datatype'=>"/^\s*$|^\d{4}\-\d{1,2}\-\d{1,2}\s{1}(\d{1,2}:){2}\d{1,2}$/" ,
                        'errormsg'=>"请选择正确的日期",
                    ),$attr)
                ),$otherParam);
                return $basic;
                break;
            default:
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        //nothing
                    ),$attr),
                ),$otherParam);
                return $basic;
        }
    }



}
